package besta.moon.engine.store;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.sql.SQLException;

import besta.moon.MoonException;
import besta.moon.engine.TransactionStep;

public class MoonPage extends TransactionStep {

    protected byte[] page;
    int pageSize;
    public long fileOffset; 

    public MoonPage(byte[] page, int pageSize, FileChannel raFile, long fileOffset) {
        super(raFile);
        this.page = page;
        this.pageSize = pageSize;
        this.fileOffset = fileOffset;
    }

    final void setPageData(byte[] data, int size) {
        page = data;
        pageSize = size;
    }

    @Override
    public long commit() throws SQLException {
        try {
            if (raFile != null && page != null) {
                ByteBuffer buffer = ByteBuffer.wrap(page, 0, pageSize);
                synchronized (raFile) {
                    if (fileOffset < 0) {
                        fileOffset = raFile.size();
                    }
                    raFile.position(fileOffset);
                    raFile.write(buffer);
                }
            }
            return fileOffset;
        } catch (IOException e) {
            throw MoonException.createFromException(e);
        }
    }

    @Override
    public final void rollback() {
        raFile = null;
    }
}
